package com.gc.framework.util;

import java.io.File;
import java.io.IOException;

import com.gc.common.utils.StringUtils;
import com.gc.common.utils.file.MimeTypeUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.springframework.web.multipart.MultipartFile;

import com.gc.common.config.Global;
import com.gc.common.exception.file.FileNameLengthLimitExceededException;
import com.gc.common.utils.Md5Utils;

/**
 * 文件上传工具类
 *
 * @author gc
 */
public class FileUploadUtils {
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 52428800;

    /**
     * 默认上传的地址
     */
    private static String defaultBaseDir = Global.getProfile();

    /**
     * 默认的文件名最大长度
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 200;

    /**
     * 默认文件类型jpg
     */
    public static final String IMAGE_JPG_EXTENSION = ".jpg";

    private static int counter = 0;

    public static void setDefaultBaseDir(String defaultBaseDir) {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir() {
        return defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload(MultipartFile file) throws IOException {
        try {
            return upload(getDefaultBaseDir(), file, FileUploadUtils.IMAGE_JPG_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException {
        try {
            return upload(baseDir, file, FileUploadUtils.IMAGE_JPG_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String uploadApk(String baseDir, MultipartFile file,String extension) throws IOException {
        try {
            return upload(baseDir, file, extension);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir   相对应用的基目录
     * @param file      上传的文件
     * @param extension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     */
    public static final String upload(String baseDir, MultipartFile file, String extension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException {

        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(file.getOriginalFilename(), fileNamelength,
                    FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file);

        String fileName = encodingFilename(file.getOriginalFilename(), extension);

        File desc = getAbsoluteFile(baseDir, baseDir + fileName);
        file.transferTo(desc);
        return fileName;
    }

    private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException {
        File desc = new File(File.separator + filename);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }

    /**
     * 编码文件名
     */
    private static final String encodingFilename(String filename, String extension) {
        filename = filename.replace("_", " ");
        filename = Md5Utils.hash(filename + System.nanoTime() + counter++) + extension;
        return filename;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     */
    public static final void assertAllowed(MultipartFile file) throws FileSizeLimitExceededException {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException("not allowed upload upload", size, DEFAULT_MAX_SIZE);
        }
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
    {
        for (String str : allowedExtension)
        {
            if (str.equalsIgnoreCase(extension))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 校验文件类型，保存iconUrl
     * @param extension
     * @return
     */
    public static String checkAttachSaveIcon(String extension){

        /**
         *   icon:
         *
         *   exeUrl: https://qiaolian.denajia.com/static/icon/exe.png
         *   gifUrl: https://qiaolian.denajia.com/static/icon/gif.png
         *   jpgUrl: https://qiaolian.denajia.com/static/icon/jpg.png
         *   mp3Url: https://qiaolian.denajia.com/static/icon/mp3.png
         *   wordUrl: https://qiaolian.denajia.com/static/icon/word.png
         *   pdfUrl: https://qiaolian.denajia.com/static/icon/pdf.png
         *   pngUrl: https://qiaolian.denajia.com/static/icon/png.png
         *   pptUrl: https://qiaolian.denajia.com/static/icon/ppt.png
         *   txtUrl: https://qiaolian.denajia.com/static/icon/txt.png
         *   videoUrl: https://qiaolian.denajia.com/static/icon/video.png
         *   zipUrl: https://qiaolian.denajia.com/static/icon/zip.png
         *   excel: https://qiaolian.denajia.com/static/icon/excel.png
         *
         *
         * */
        String  iconUrl = "";
        //exe
        if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.EXE_EXTENSION)){
            iconUrl = Global.getConfig("icon.exeUrl");
        }
        //gif
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.GIF_EXTENSION)){
            iconUrl = Global.getConfig("icon.gifUrl");
        }
        //jpg
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.JPG_EXTENSION)){
            iconUrl = Global.getConfig("icon.jpgUrl");
        }
        //mp3
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.MUSIC_EXTENSION)){
            iconUrl = Global.getConfig("icon.mp3Url");
        }
        //word
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.WORD_EXTENSION)){
            iconUrl = Global.getConfig("icon.wordUrl");
        }
        //pdf
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.PDF_EXTENSION)){
            iconUrl = Global.getConfig("icon.pdfUrl");
        }
        //png
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.PNG_EXTENSION)){
            iconUrl = Global.getConfig("icon.pngUrl");
        }
        //ppt
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.PPT_EXTENSION)){
            iconUrl = Global.getConfig("icon.pptUrl");
        }
        //txt
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.TXT_EXTENSION)){
            iconUrl = Global.getConfig("icon.txtUrl");
        }
        //video
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.VIDEO_EXTENSION)){
            iconUrl = Global.getConfig("icon.videoUrl");
        }
        //zip
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.ZIP_EXTENSION)){
            iconUrl = Global.getConfig("icon.zipUrl");
        }
        //excel
        else if(FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.EXCEL_EXTENSION)){
            iconUrl = Global.getConfig("icon.excelUrl");
        }
        return iconUrl;
    }
}
